package com.zjs.server.mongodb.service.Impl;

import com.mongodb.WriteResult;
import com.zjs.server.mongodb.pojo.Person;
import com.zjs.server.mongodb.service.ServicePerson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class ServicePersonImpl implements ServicePerson {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public String addPerson(Person person) {
        mongoTemplate.insert(person);
        return "添加成功";
    }

    @Override
    public String deletePerson(String name) {
        Query query = Query.query(Criteria.where("name").is(name));
        WriteResult wr = mongoTemplate.remove(query,"person");
        return wr.getN()+"  受影响的行数";
    }

    @Override
    public String updatePerson(Person person) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(person.getName()));
        Update update = new Update();
        update.set("pwd",person.getPwd());
        update.set("age",person.getAge());

        WriteResult wr = mongoTemplate.updateFirst(query,update,"person");
        return wr.getN()+"";
    }

    @Override
    public Person findPerson(String name) {
        Query query = Query.query(Criteria.where("name").is(name));
        return  mongoTemplate.findOne(query,Person.class,"person");
    }
}
